package com.tjtt.gwm.action;

import java.io.File;
import jxl.Sheet;
import jxl.Workbook;
import java.util.Calendar;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import sun.nio.cs.ext.EUC_CN;

import com.sun.org.apache.bcel.internal.generic.NEW;
import com.tjtt.common.utils.ExcelExportUtil;
import com.tjtt.common.utils.TotalFlowXmlTool;
import com.tjtt.gwm.bean.EEPRelations;
import com.tjtt.gwm.bean.EPInStore;
import com.tjtt.gwm.bean.EquipmentParts;
import com.tjtt.gwm.bean.Gongyingshang;
import com.tjtt.gwm.bean.SheBeiWeiBaoXiangMuKu;
import com.tjtt.gwm.bean.Shebeifengcun;
import com.tjtt.gwm.bean.TdmEquipment;
import com.tjtt.gwm.bean.Weituodan;
import com.tjtt.gwm.service.EEPRelationsService;
import com.tjtt.gwm.service.EquipmentPartsService;
import com.tjtt.tdm.base.BaseAction;
import com.tjtt.tdm.base.PageResult;
import com.tjtt.tdm.base.PubMethod;
import com.tjtt.tdm.base.StringUtil;
import com.tjtt.tdm.flow.bean.FlowTask;
import com.tjtt.tdm.flow.bean.FlowTaskInfo;
import com.tjtt.tdm.flow.bean.Flowstate;
import com.tjtt.tdm.form.service.IAutoService;

import com.tjtt.tdm.codeReview.service.ICodeReviewService;
import com.tjtt.tdm.flow.bean.Flowtype;
import com.tjtt.tdm.flow.service.IFlowformService;
import com.tjtt.tdm.flow.service.IFlowtypeService;

public class EquipmentPartsAction extends BaseAction {

	private EquipmentPartsService equipmentPartsService;
	private EEPRelationsService eepRelationsService;
	private Flowtype flowtype;
	private File filePath;
	
	public File getFilePath() {
		return filePath;
	}

	public void setFilePath(File filePath) {
		this.filePath = filePath;
	}


	WebApplicationContext factory = WebApplicationContextUtils
			.getRequiredWebApplicationContext(ServletActionContext
					.getServletContext());
	private ICodeReviewService codeReviewService = (ICodeReviewService) factory
			.getBean("codeReviewService");

	private EquipmentParts ep = new EquipmentParts();

	private EPInStore epis = new EPInStore();

	public EquipmentPartsService getEquipmentPartsService() {
		return equipmentPartsService;
	}

	public void setEquipmentPartsService(
			EquipmentPartsService equipmentPartsService) {
		this.equipmentPartsService = equipmentPartsService;
	}

	public EEPRelationsService getEepRelationsService() {
		return eepRelationsService;
	}

	public void setEepRelationsService(EEPRelationsService eepRelationsService) {
		this.eepRelationsService = eepRelationsService;
	}

	public EquipmentParts getEp() {
		return ep;
	}

	public void setEp(EquipmentParts ep) {
		this.ep = ep;
	}

	public EPInStore getEpis() {
		return epis;
	}

	public void setEpis(EPInStore epis) {
		this.epis = epis;
	}

	public String flowStart() {
		String mainid = this.getRequest().getParameter("mainid");
		String flowid = this.getRequest().getParameter("flowid");
		String stateid = this.getRequest().getParameter("stateid");
		getRequest().setAttribute("flowid", flowid);
		getRequest().setAttribute("stateid", stateid);
		String epInstoreno;
		if (mainid == null || mainid.equals("")) {
			String epids = this.getRequest().getParameter("epids");
			String username = this.getUserNM();
			String userid = this.getUserId();
			System.out.println("---username:--------"+username);
			String epInsqdepid = this.getDeptid();
			String epInsqdep = this.getDeptName();
			Date dt = new Date();
			SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
			String epInstoredate = matter1.format(dt);
			getRequest().setAttribute("epids", epids);
			getRequest().setAttribute("username", username);
			getRequest().setAttribute("userid", userid);
			getRequest().setAttribute("epInsqdepid", epInsqdepid);
			getRequest().setAttribute("epInsqdep", epInsqdep);
			getRequest().setAttribute("epInstoredate", epInstoredate);
			// 删除冗余数据
			deleteEPInStoreData();
			epInstoreno = addepinfo(epids);
			getRequest().setAttribute("epInstoreno", epInstoreno);
			super.initFlowaddBase();
		} else {
			EPInStore a = equipmentPartsService.queryEPInStoreByMainId(mainid);
			epInstoreno = a.getEpInstoreno();
			String username = equipmentPartsService.queryUsersName(
					a.getEpInsqr()).getUsername();
			String epInsqdepname = equipmentPartsService.queryOrganizationName(
					a.getEpInsqdep()).getOrgName();
			String username1 = equipmentPartsService.queryUsersName(
					a.getEpInshr()).getUsername();
			getRequest().setAttribute("epInstoreno", epInstoreno);
			getRequest().setAttribute("username", username);
			getRequest().setAttribute("username1", username1);
			getRequest().setAttribute("userid", a.getEpInsqr());
			getRequest().setAttribute("userid1", a.getEpInshr());
			getRequest().setAttribute("epInsqdepid", a.getEpInsqdep());
			getRequest().setAttribute("epInsqdep", epInsqdepname);
			getRequest().setAttribute("epInshrq", a.getEpInshrq());
			getRequest().setAttribute("epInstoredate", a.getEpInstoredate());
			getRequest().setAttribute("epRemark", a.getEpRemark());
			super.initFlowupdateBase();
		}

		return "flowStart";
	}

	// ----------------条件查询备件台账---------------------------------------------
	public void queryDataList() throws Exception {
		try {
			String epName = StringUtil.encodingUrl(getRequest().getParameter(
					"epName"));
			String epCode = StringUtil.encodingUrl(getRequest().getParameter(
					"epCode"));
			String choose = StringUtil.encodingUrl(getRequest().getParameter(
					"choose"));
			String ids = StringUtil.encodingUrl(getRequest()
					.getParameter("ids")); // 国伟添加的根据IDS查询

			Map<String, String> filterMap = getPagerMap();
			if (null != epName && !"".equals(epName)) {
				epName = StringUtil.encodingUrl(epName);
				filterMap.put("epName", epName);
			}
			if (null != epCode && !"".equals(epCode)) {
				epCode = StringUtil.encodingUrl(epCode);
				filterMap.put("epCode", epCode);
			}
			if (null != choose && !"".equals(choose)) {
				choose = StringUtil.encodingUrl(choose);
				filterMap.put("choose", choose);
			}

			if (null != ids && !"".equals(ids)) {
				ids = StringUtil.encodingUrl(ids);
				filterMap.put("ids", ids);// 国伟添加的IDS
			}

			PageResult result = equipmentPartsService.queryDataList(filterMap);
			String[] viewArray = { "id", "epStorehouse", "epCode", "epName",
					"epProperty", "epLevel", "epGuige", "epBrand",
					"epSupplier", "epAverageprice", "epCycle", "epMaxstock",
					"epMinstock", "epActualstock", "epStockstate",
					"epMeasurementunit", "epStoragelocation", "epRemark" };
			String str = getColumnJson(result, viewArray);
			System.out.println("------------------" + str);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("application/XML,charset=GBK");
			response.setHeader("Charset", "GBK");
			response.setCharacterEncoding("GBK");
			response.setContentType("text/xml");
			PrintWriter out = getResponse().getWriter();
			out.print(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// ----------------根据入库单号查询备件列表---------------------------------------------
	public void queryEPDataListByids() throws Exception {
		try {
			String epInstoreno = getRequest().getParameter("epInstoreno");
			Map<String, String> filterMap = getPagerMap();
			if (null != epInstoreno && !"".equals(epInstoreno)) {
				epInstoreno = StringUtil.encodingUrl(epInstoreno);
				filterMap.put("epInstoreno", epInstoreno);
			}

			PageResult result = equipmentPartsService
					.queryEPDataListByids(filterMap);
			String[] viewArray = { "id", "epid", "epStorehouse", "epCode",
					"epName", "epProperty", "epLevel", "epGuige", "epBrand",
					"epSupplier", "epInstoreprice", "epIncycle", "epMaxstock",
					"epMinstock", "epActualstock", "epInstorenum",
					"epInstoremoney", "epInactualnum", "epMeasurementunit",
					"epApplicableequipment", "epApplicableequipmentid",
					"epStoragelocation" };
			String str = getColumnJson(result, viewArray);
			System.out.println("*******************" + str);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("application/XML,charset=GBK");
			response.setHeader("Charset", "GBK");
			response.setCharacterEncoding("GBK");
			response.setContentType("text/xml");
			PrintWriter out = getResponse().getWriter();
			out.print(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// ---------------------详细信息查看------------------------------------------
	public String queryDataById() throws Exception {
		try {
			String id = getRequest().getParameter("id");
			ep = equipmentPartsService.queryDataById(id);
			return "chakan";
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}
	// ---------------------备件信息修改-页面跳转-----------------------------------------
	public String updateDataById() throws Exception {
		try {
			String id = getRequest().getParameter("id");
			ep = equipmentPartsService.queryDataById(id);
			EquipmentParts aa=equipmentPartsService.queryEPDataById(id);
			String epStorehouseid=aa.getEpStorehouse();
			String epSupplierid=aa.getEpSupplier();
			getRequest().setAttribute("epStorehouseid", epStorehouseid);
			getRequest().setAttribute("epSupplierid", epSupplierid);
			return "updateEP";
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}
	
	// ------------------------------数据导出功能----------------------------------------
	public void exportExcel() {
		try {
			List<String> list = new ArrayList<String>();
			List<String> facefieldlist = new ArrayList<String>();
			List<String> fieldlist = new ArrayList<String>();
			List<String> fieldlist1 = new ArrayList<String>();
			String extitleName = "";
			String titleNames = StringUtil.escapeString(getRequest()
					.getParameter("titleNames"));
			String facefieldsNames = getRequest().getParameter("fieldsNames");

			String epName = StringUtil.encodingUrl(getRequest().getParameter(
					"epName"));
			String epCode = StringUtil.encodingUrl(getRequest().getParameter(
					"epCode"));
			String choose = StringUtil.encodingUrl(getRequest().getParameter(
					"choose"));

			StringBuilder fieldsNames = new StringBuilder();
			fieldsNames
					.append("id&epStorehouse&epCode&epName&epProperty&epLevel&epGuige"
							+ "&epBrand&epSupplier&epAverageprice&epCycle&epMaxstock&epMinstock"
							+ "&epActualstock&epStockstate&epMeasurementunit&epStoragelocation&epRemark");
			if (!"".equals(titleNames) && titleNames != null) {
				try {
					extitleName = new String(titleNames.getBytes("ISO8859-1"),
							"UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

				String[] titleName = extitleName.split(",");// 前台中文名称
				for (int i = 0; i < titleName.length; i++) {
					list.add(titleName[i]);
				}

				String[] facefieldsName = facefieldsNames.toString().split(",");// 前台字段名称
				for (int j = 0; j < facefieldsName.length; j++) {
					facefieldlist.add(facefieldsName[j].toUpperCase());
				}

				String[] fieldsName = fieldsNames.toString().split("&");// 后台字段名称
				for (int j = 0; j < fieldsName.length; j++) {
					fieldlist.add(fieldsName[j].toUpperCase());
				}

				/***
				 * excel显示字段 18
				 */
				String[] s = { "epStorehouse", "epCode", "epName",
						"epProperty", "epLevel", "epGuige", "epBrand",
						"epSupplier", "epAverageprice", "epCycle",
						"epMaxstock", "epMinstock", "epActualstock",
						"epStockstate", "epMeasurementunit",						
						"epStoragelocation", "epRemark" };
				for (int i = 0; i < s.length; i++) {
					fieldlist1.add(s[i].toUpperCase());
				}
			}
			String fileName = "设备备件台账信息.xls";

			Map<String, Object> filterMap = getPagerMap();
			// 解决乱码问题
			/*
			 * if (equipmentNo != null && !"".equals(equipmentNo)) { equipmentNo
			 * = StringUtil.encodingUrl(equipmentNo); }
			 */

			// 将查询条件保存到Map里
			if (null != epName && !"".equals(epName)) {
				epName = StringUtil.encodingUrl(epName);
				filterMap.put("epName", epName);
			}
			if (null != epCode && !"".equals(epCode)) {
				epCode = StringUtil.encodingUrl(epCode);
				filterMap.put("epCode", epCode);
			}
			if (null != choose && !"".equals(choose)) {
				choose = StringUtil.encodingUrl(choose);
				filterMap.put("choose", choose);
			}

			ExcelExportUtil excelutil = new ExcelExportUtil();
			List listtitle = excelutil.getTitleDataList(fieldlist1, excelutil
					.getMapDataList(facefieldlist, list));

			filterMap.put("rows", 999);// 放在一页显示Excel信息
			List setListForExcel = equipmentPartsService.queryDataList(
					filterMap).getData();

			excelutil.exportlhExcel3(fileName, listtitle, fieldlist1,
					fieldlist, filterMap, setListForExcel);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// ---------------------备件入库申请单备件信息添加-----------------------------
	public String addepinfo(String epid) {
		String[] epids = epid.split(",");
		String danhao = equipmentPartsService.queryMaxRKNo();
		String epInstoreno = "CY-RK-";
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		if (danhao == null || danhao.equals("")) {
			epInstoreno = epInstoreno + year + "-0001";
		} else {
			String newdanhao = danhao.substring(danhao.length() - 4);
			String oldyear = danhao.substring(6, 10);
			int a = Integer.parseInt(newdanhao) + 1;
			epInstoreno = epInstoreno + year + "-";
			if (oldyear.equals(year + "")) {
				if (a < 10) {
					epInstoreno = epInstoreno + "000" + a;
				} else if (a > 999) {
					epInstoreno = epInstoreno + a;
				} else if (a > 99&& a<1000) {
					epInstoreno = epInstoreno + "0" + a;
				} else if (a > 9 && a < 100) {
					epInstoreno = epInstoreno + "00" + a;
				}
			} else {
				epInstoreno = epInstoreno + "0001";
			}
		}
		Date dt=new Date();     
	    SimpleDateFormat matter1=new SimpleDateFormat("yyyy-MM-dd");
	    String date=matter1.format(dt);
		int j = epids.length;
		for (int i = 0; i < j; i++) {
			EquipmentParts e = equipmentPartsService
					.queryEPYuanListById(epids[i]);
			EPInStore es = new EPInStore();
			es.setEpInstoreno(epInstoreno);
			es.setEpInstoredate(date);
			es.setEpStorehouse(e.getEpStorehouse());
			es.setEpId(e.getId() + "");
			es.setEpCode(e.getEpCode());
			es.setEpName(e.getEpName());
			es.setEpProperty(e.getEpProperty());
			es.setEpLevel(e.getEpLevel());
			es.setEpGuige(e.getEpGuige());
			es.setEpBrand(e.getEpBrand());
			es.setEpSupplier(e.getEpSupplier());
			es.setEpMaxstock(Integer.parseInt(e.getEpMaxstock() + ""));
			es.setEpMinstock(Integer.parseInt(e.getEpMinstock() + ""));
			es.setEpActualstock(Integer.parseInt(e.getEpActualstock() + ""));
			es.setEpMeasurementunit(e.getEpMeasurementunit());
			es.setEpApplicableequipment(e.getEpApplicableequipment());
			es.setEpApplicableequipmentid(e.getEpApplicableequipmentid());
			es.setEpStoragelocation(e.getEpStoragelocation());
			es.setEpInstorenum(0);
			es.setEpInstoreprice(0.0);
			es.setEpInstoremoney(0.0);
			es.setEpIncycle("0");
			equipmentPartsService.addepInStore(es);
		}
		return epInstoreno;

	}

	// ---------------------备件入库申请单-备件信息更新-----------------------------
	public void updateEPInstoreInfo() {
		String id = getRequest().getParameter("id");
		EPInStore epis1 = equipmentPartsService.queryEPInStoreByMainId(id);
		String inNo = getRequest().getParameter("epInstorenum");
		String inP = getRequest().getParameter("epInstoreprice");
		String inANo = getRequest().getParameter("epInactualnum");
		String epIncycle = getRequest().getParameter("epIncycle");
		int epInstorenum = 0;
		double epInstoreprice = 0.0;
		double epInstoremoney = 0.0;
		int epInactualnum = 0;
		try {
			if (!(inNo == null || inNo.equals(""))) {
				epInstorenum = new Integer(inNo);
				epis1.setEpInstorenum(epInstorenum);
			}
			if (!(inP == null || inP.equals(""))) {
				epInstoreprice = new Double(inP);
				epis1.setEpInstoreprice(epInstoreprice);
			}
			if (!(epIncycle == null || epIncycle.equals(""))) {
				epis1.setEpIncycle(epIncycle);
			}
			if (!(inANo == null || inANo.equals(""))) {
				epInactualnum = new Integer(inANo);
				epis1.setEpInactualnum(epInactualnum);
			}
			if (epInstorenum > 0 && epInstoreprice > 0 && epInactualnum > 0) {
				epInstoremoney = epInstorenum * epInstoreprice;
				epis1.setEpInstoremoney(epInstoremoney);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

		equipmentPartsService.updateEPINfoByEPIdAndNo(epis1);
	}

	// ---------------------备件入库申请单-备件列表详细信息查看-----------------------------
	public String queryEPInstoreViewById() {
		try {
			String id = getRequest().getParameter("id");
			epis = equipmentPartsService.queryEPINfoByEPIdAndNo(id);
			ep=equipmentPartsService.queryDataById(epis.getEpId());
			return "inStoreView";
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// ---------------------备件入库申请单-备件列表信息添加-----------------------------
	public String addEPInstoreView() {
		String epInstoreno = getRequest().getParameter("epInstoreno");
		getRequest().setAttribute("epInstoreno", epInstoreno);
		return "inStoreAdd";
	}

	// ---------------------备件入库信息更新及提交-----------------------------
	public void addepInStore() throws IOException {
		String flag = this.getRequest().getParameter("flag");
		PrintWriter out = getResponse().getWriter();
		try {
			String flowname = getRequest().getParameter("flowname");
			String epInstoreno = getRequest().getParameter("epInstoreno");
			String epInstoredate = getRequest().getParameter("epInstoredate");
			String epInstoretype = getRequest().getParameter("epInstoretype");
			String epInsqdep = getRequest().getParameter("epInsqdep");
			String epInsqr = getRequest().getParameter("epInsqr");
			String epInshr = getRequest().getParameter("epInshr");
			String epInshrq = getRequest().getParameter("epInshrq");
			String epFlowstate = "提交";
			String epRemark = getRequest().getParameter("epRemark");
			String aString = "id,epInstoreno,epInstoredate,epInstoretype,epInsqdep,epInsqr,epId,epStorehouse,epCode,epName"
					+ ",epProperty,epLevel,epGuige,epBrand,epSupplier,epMaxstock,epMinstock,epActualstock,epMeasurementunit,epApplicableequipment,epApplicableequipmentid,epStoragelocation,epInstorenum,epInstoreprice,epInstoremoney,epIncycle,epInshr,epInshrq,epInactualnum,epFlowstate,epRemark";
			int id = 0;
           String nextUserID=this.getRequest().getParameter("cgyID");
           String nextUserName=this.getRequest().getParameter("cgy");
			List<EPInStore> list = equipmentPartsService.queryEPINfoByEPInNo(epInstoreno);
			Iterator iter = list.iterator();
			while (iter.hasNext()) {
				EPInStore ep = new EPInStore();
				Object[] b = (Object[]) iter.next();
				BigDecimal id1 = (BigDecimal) b[5];
				id = id1.intValue();
				ep=equipmentPartsService.queryEPINfoByEPId(id+"");
				ep.setEpInstoreno(epInstoreno);
				ep.setEpInstoredate(epInstoredate);
				ep.setEpInstoretype(epInstoretype);
				ep.setEpInsqdep(epInsqdep);
				ep.setEpInsqr(epInsqr);
				ep.setEpInshr(epInshr);
				ep.setEpInshrq(epInshrq);
				ep.setEpFlowstate(epFlowstate);
				ep.setEpRemark(epRemark);
				equipmentPartsService.updateEPINfoByEPIdAndNo(ep);
			}

			// 保存到待办页面
			String mainid = id + "";// epis.getEpInstoreno();
			if (flag.equals("0")) {
				super.saveFaqiBase("TDM_EPINSTORE", mainid);
				List flist=equipmentPartsService.getFlowtaskId("TDM_EPINSTORE", mainid);
				  if(null != flist && flist.size()>0){
					  FlowTaskInfo flowtaskinfo = equipmentPartsService.getFlowTaskInfo(flist.get(0).toString());
				      flowtaskinfo.setNextUsersId(","+nextUserID+",");
				      flowtaskinfo.setNextUsersName(","+nextUserName+",");
				      equipmentPartsService.updateFlowTaskInfo(flowtaskinfo);
				  }
			} else if (flag.equals("1")) {
				super.saveUpdateBase("TDM_EPINSTORE", mainid);
				List flist=equipmentPartsService.getFlowtaskId("TDM_EPINSTORE", mainid);
				  if(null != flist && flist.size()>0){
					  FlowTaskInfo flowtaskinfo = equipmentPartsService.getFlowTaskInfo(flist.get(0).toString());
				      flowtaskinfo.setNextUsersId(","+nextUserID+",");
				      flowtaskinfo.setNextUsersName(","+nextUserName+",");
				      equipmentPartsService.updateFlowTaskInfo(flowtaskinfo);
				  }
			}
			// String result=super.saveFaqiBase("TDM_EPINSTORE",mainid);

			// 删除冗余数据
			deleteEPInStoreData();

			getRequest().setAttribute("message", "提交成功!");
			out.print("{\"result\":\"success\"}");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			getRequest().setAttribute("message", "提交失败");
			out.print("{\"result\":\"error\"}");
		}
	}

	// ---------------------备件入库信息审核-----------------------------
	public void shenheEPInStore() throws IOException {
		String id2 = getRequest().getParameter("id");
		String epRemark1 = getRequest().getParameter("epRemark");
		String steptype=this.getRequest().getParameter("steptype");
   	 
   	     String actionType="通过申请";
   	    if(steptype.equals("step2")){
   		 actionType="退回申请";
   	     }
		// 更新flowtask表
		//super.saveUpdateExtend("TDM_EPINSTORE", id2, actionType, epRemark1);
		String taskinfoid = getRequest().getParameter("taskinfoid");
		IFlowtypeService flowtypeService = getFlowtypeService();
		IFlowformService flowformService = getFlowformentityService();
		FlowTaskInfo flowtaskinfo = flowformService
				.getFlowTaskInfoById(taskinfoid);
		String taskid = flowtaskinfo.getFlowtaskid().toString();
		FlowTask flowTask = flowformService.getFlowTaskById(taskid);
		String state = flowTask.getFlowStateId();
		PrintWriter out = getResponse().getWriter();
		try {

			String epFlowstate1;
			String epInstoreno1 = getRequest().getParameter("epInstoreno");
			String epInshr1 = getRequest().getParameter("epInshr");
			String epInshrq1 = getRequest().getParameter("epInshrq");
			if (state.equals("end")) {
				epFlowstate1 = "通过";
			} else {
				epFlowstate1 = "退回";
			}
			List<EPInStore> list = equipmentPartsService.queryEPINfoByEPInNo(epInstoreno1);
			Iterator iter = list.iterator();
			EPInStore in[] = new EPInStore[list.size()];
			int i = 0;
			while (iter.hasNext()) {
				Object[] b = (Object[]) iter.next();
				EPInStore ep = new EPInStore();
				BigDecimal id1 = (BigDecimal) b[5];
				int id = id1.intValue();
				ep=equipmentPartsService.queryEPINfoByEPId(id+"");
				ep.setEpInshr(epInshr1);
				ep.setEpInshrq(epInshrq1);
				ep.setEpFlowstate(epFlowstate1);
				ep.setEpRemark(epRemark1);
				equipmentPartsService.updateEPINfoByEPIdAndNo(ep);
				in[i] = ep;
				i++;
			}
			 String nextUserID=equipmentPartsService.queryEPINfoByEPIdAndNo(id2).getEpInsqr();
	 	     String nextUserName=equipmentPartsService.queryUsersName(nextUserID).getUsername();
	 	     List flowlist=equipmentPartsService.getFlowtaskId("TDM_EPINSTORE", id2);
			 if(null != flowlist && flowlist.size()>0){
					  String id=flowlist.get(0).toString();
					  FlowTaskInfo flowtaskinfo1 = equipmentPartsService.getFlowTaskInfo(flowlist.get(0).toString());
					  flowtaskinfo1.setNextUsersId(","+nextUserID+",");
					  flowtaskinfo1.setNextUsersName(","+nextUserName+",");
					  equipmentPartsService.updateFlowTaskInfo(flowtaskinfo1);
				  }
			// 更新备件台账信息
			
			 if( actionType.equals("通过申请")){
				 updateEquipmentParts(in);
		   	     }

			out.print("{\"result\":\"success\"}");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			out.print("{\"result\":\"error\"}");
		}
	}

	/*
	 * 入库后更新备件台账
	 */
	public void updateEquipmentParts(EPInStore in[]) {

		for (int i = 0; i < in.length; i++) {
			if (in[i].getEpFlowstate().equals("通过")) {
				String epid = in[i].getEpId();
				EquipmentParts ep = new EquipmentParts();
				ep = equipmentPartsService.queryEPDataById(epid);
				DecimalFormat df = new DecimalFormat(".##");
				if (ep.getId() != null) {
					double averagePrice = new Double(ep.getEpAverageprice());
					double sumMoney = (ep.getEpActualstock().intValue())
							* averagePrice + in[i].getEpInactualnum()
							* in[i].getEpInstoreprice();
					int sumNo = ep.getEpActualstock().intValue()
							+ in[i].getEpInactualnum();
					String cycleAver = ep.getEpCycle();
					int epCycle = (Integer.parseInt(cycleAver) + Integer
							.parseInt(in[i].getEpIncycle())) / 2;
					averagePrice = new Double(df.format(sumMoney / sumNo));
					ep.setEpAverageprice(averagePrice + "");
					BigDecimal epActualstock = new BigDecimal(sumNo);
					ep.setEpActualstock(epActualstock);
					ep.setEpCycle(epCycle + "");
					ep.setEpIsky("0");
					equipmentPartsService.updateEquipmentParts(ep);
				}
			}
		}

	}

	/*
	 * 出库后更新备件台账
	 */
	public void updateEquipmentPartsByOut(String id, String outNum) {
		EquipmentParts eParts = equipmentPartsService.queryEPDataById(id);
		int anum = eParts.getEpActualstock().intValue();
		int onum = Integer.parseInt(outNum);
		int newnum = anum - onum;
		BigDecimal epActualstock = new BigDecimal(newnum);
		eParts.setEpActualstock(epActualstock);
		equipmentPartsService.updateEquipmentParts(eParts);
	}

	/*
	 * 删除冗余数据
	 */
	public void deleteEPInStoreData() {
		// String epInstoreno
		List<EPInStore> deleteList = equipmentPartsService
				.queryEPINfoByEPInNo(null);
		if (deleteList.size() > 0&&deleteList!=null) {
			Iterator iter = deleteList.iterator();
			while (iter.hasNext()) {
				EPInStore ep = new EPInStore();
				Object[] b = (Object[]) iter.next();
				String epInstoredate = (String) b[1];
				BigDecimal id1 = (BigDecimal) b[5];
				int id = id1.intValue();
				ep=equipmentPartsService.queryEPINfoByEPId(id+"");
				Date dt=new Date();     
        	    SimpleDateFormat matter1=new SimpleDateFormat("yyyy-MM-dd");
        	    String date=matter1.format(dt);
        	    String[] now = date.split("-");
        	    String nowy=now[0];
        	    String nowm=now[1];
        	    String nowd=now[2];
        	    String[] e = epInstoredate.split("-");
        	    String ey=e[0];
        	    String em=e[1];
        	    String ed=e[2];
                if(nowy.equals(ey)){
                	if(nowm.equals(em)){
                		int nowday=Integer.parseInt(nowd);
                		int eday=Integer.parseInt(ed);
                		int a=nowday-eday;
                		if(a>1){
                			equipmentPartsService.deleteEPInData(ep);
                		}
                	}
                	else{
                		equipmentPartsService.deleteEPInData(ep);
                	}
                }
                else{
                	equipmentPartsService.deleteEPInData(ep);
                }
              }
            }       	
	}

	/*
	 * 根据id获取设备备件入库信息流程处理页面
	 */
	public String queryEPInStoreChuLiById() {
		String mainid = getRequest().getParameter("mainid");
		epis = equipmentPartsService.queryEPInStoreByMainId(mainid);
		String epInsqrname = equipmentPartsService.queryUsersName(
				epis.getEpInsqr()).getUsername();
		String epInsqdepname = equipmentPartsService.queryOrganizationName(
				epis.getEpInsqdep()).getOrgName();
		String flowid = this.getRequest().getParameter("flowid");
		String flowname = this.getRequest().getParameter("flowname");
		String stateid = this.getRequest().getParameter("stateid");
		String username = this.getUserNM();
		String userid = this.getUserId();
		Date dt = new Date();
		SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
		String epInshrq = matter1.format(dt);
		getRequest().setAttribute("flowid", flowid);
		getRequest().setAttribute("stateid", stateid);
		getRequest().setAttribute("username", username);
		getRequest().setAttribute("userid", userid);
		getRequest().setAttribute("epInshrq", epInshrq);
		getRequest().setAttribute("flowname", flowname);
		getRequest().setAttribute("epInsqrname", epInsqrname);
		getRequest().setAttribute("epInsqdepname", epInsqdepname);
		getRequest().setAttribute("epInstoreno", epis.getEpInstoreno());
		getRequest().setAttribute("epInstoredate", epis.getEpInstoredate());
		getRequest().setAttribute("epInstoretype", epis.getEpInstoretype());
		// getRequest().setAttribute("epInsqdep", epis.getEpInsqdep());
		// getRequest().setAttribute("epInsqr", epis.getEpInsqr());
		super.initFlowupdateBase();
		return "flowEnd";
	}

	/**
	 * 
	 * 描述：查询流程路径
	 * 
	 * @author wangxd
	 * @date Jul 1, 2015 10:37:08 AM
	 * @return String
	 * @throw
	 */
	public String getPath(String flowid) {
		Long ids = Long.parseLong(flowid);// 241为流程实例的id
		flowtype = codeReviewService.findFileNameById(ids);
		String filename = flowtype.getFilename();
		String path = PubMethod.GetFlowFilePath() + filename;
		return path;
	}

	// ---------------------备件入库流程退回-----------------------------
	public void epInStoreFailure() throws IOException {
		PrintWriter out = getResponse().getWriter();
		try {
			String id = getRequest().getParameter("id");

			// 更新flowtask表
			super.backUpdateBase(true);
			out.print("{\"result\":\"success\"}");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			out.print("{\"result\":\"error\"}");
		}

	}

	// ---------------------选择设备列表-----------------------------
	public void queryEP() throws Exception {
		try {
			String epName = getRequest().getParameter("epName");
			String epNo = getRequest().getParameter("epNo");
			Map<String, String> filterMap = getPagerMap();
			if (null != epName && !"".equals(epName)) {
				epName = StringUtil.encodingUrl(epName);
				filterMap.put("epName", epName);
			}
			if (null != epNo && !"".equals(epNo)) {
				epNo = StringUtil.encodingUrl(epNo);
				filterMap.put("epNo", epNo);
			}
			PageResult result = equipmentPartsService.queryEP(filterMap);
			String[] viewArray = { "ID", "EQU_NAME", "EQU_NO" };
			String str = getColumnJson(result, viewArray);
			// System.out.println("*******************"+str);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("application/XML,charset=GBK");
			response.setHeader("Charset", "GBK");
			response.setCharacterEncoding("GBK");
			response.setContentType("text/xml");
			PrintWriter out = getResponse().getWriter();
			out.print(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// ---------------------选择供应商列表-----------------------------
	public void queryGYS() throws Exception {
		try {
			String gysName = getRequest().getParameter("gysName");
			Map<String, String> filterMap = getPagerMap();
			if (null != gysName && !"".equals(gysName)) {
				gysName = StringUtil.encodingUrl(gysName);
				filterMap.put("gysName", gysName);
			}
			PageResult result = equipmentPartsService.queryGYS(filterMap);
			String[] viewArray = { "ID", "GYS_NAME", "GYS_DIZHI" };
			String str = getColumnJson(result, viewArray);
			// System.out.println("*******************"+str);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("application/XML,charset=GBK");
			response.setHeader("Charset", "GBK");
			response.setCharacterEncoding("GBK");
			response.setContentType("text/xml");
			PrintWriter out = getResponse().getWriter();
			out.print(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// ---------------------入库申请单中添加备件列表数据-----------------------------
	public void saveEPData() throws Exception {
		PrintWriter out = getResponse().getWriter();
		try {
			// 生成备件id
			String id = equipmentPartsService.queryMaxEPNo();
			BigDecimal epid = new BigDecimal(Integer.parseInt(id) + 1);
			String epId = Integer.parseInt(id) + 1 + "";
			String epInstoreno = getRequest().getParameter("epInstoreno");
			EPInStore es = new EPInStore();
			es.setEpInstoreno(epInstoreno);
			es.setEpStorehouse(getRequest().getParameter("epStorehouse"));
			es.setEpId(epId);
			es.setEpCode(getRequest().getParameter("epCode"));
			es.setEpName(getRequest().getParameter("epName"));
			es.setEpProperty(getRequest().getParameter("epProperty"));
			es.setEpLevel(getRequest().getParameter("epLevel"));
			es.setEpGuige(getRequest().getParameter("epGuige"));
			es.setEpBrand(getRequest().getParameter("epBrand"));
			es.setEpSupplier(getRequest().getParameter("epSupplier"));
			es.setEpMaxstock(Integer.parseInt(getRequest().getParameter(
					"epMaxstock")));
			es.setEpMinstock(Integer.parseInt(getRequest().getParameter(
					"epMinstock")));
			es.setEpActualstock(Integer.parseInt(getRequest().getParameter(
					"epActualstock")));
			es.setEpMeasurementunit(getRequest().getParameter(
					"epMeasurementunit"));
			es.setEpApplicableequipment(getRequest().getParameter(
					"epApplicableequipment"));
			es.setEpApplicableequipmentid(getRequest().getParameter(
					"epApplicableequipmentid"));
			es.setEpStoragelocation(getRequest().getParameter(
					"epStoragelocation"));
			es.setEpInstorenum(Integer.parseInt(getRequest().getParameter(
					"epInstorenum")));
			es.setEpInstoreprice(Double.parseDouble(getRequest().getParameter(
					"epInstoreprice")));
			es.setEpInstoremoney(0.0);
			es.setEpIncycle(getRequest().getParameter("epIncycle"));
			equipmentPartsService.addepInStore(es);
			EquipmentParts ep = new EquipmentParts();
			ep.setId(epid);
			ep.setEpStorehouse(getRequest().getParameter("epStorehouse"));
			ep.setEpCode(getRequest().getParameter("epCode"));
			ep.setEpName(getRequest().getParameter("epName"));
			ep.setEpProperty(getRequest().getParameter("epProperty"));
			ep.setEpLevel(getRequest().getParameter("epLevel"));
			ep.setEpGuige(getRequest().getParameter("epGuige"));
			ep.setEpBrand(getRequest().getParameter("epBrand"));
			ep.setEpSupplier(getRequest().getParameter("epSupplier"));
			ep.setEpMaxstock(new BigDecimal(Integer.parseInt(getRequest()
					.getParameter("epMaxstock"))));
			ep.setEpMinstock(new BigDecimal(Integer.parseInt(getRequest()
					.getParameter("epMinstock"))));
			ep.setEpActualstock(new BigDecimal(Integer.parseInt(getRequest()
					.getParameter("epActualstock"))));
			ep.setEpMeasurementunit(getRequest().getParameter(
					"epMeasurementunit"));
			ep.setEpApplicableequipment(getRequest().getParameter(
					"epApplicableequipment"));
			ep.setEpApplicableequipmentid(getRequest().getParameter(
					"epApplicableequipmentid"));
			ep.setEpStoragelocation(getRequest().getParameter(
					"epStoragelocation"));
			ep.setEpStockstate(getRequest().getParameter("epStockstate"));
			ep.setEpRemark(getRequest().getParameter("epRemark"));
			ep.setEpAverageprice(getRequest().getParameter("epInstoreprice"));
			ep.setEpCycle(getRequest().getParameter("epIncycle"));
			ep.setEpIsky("1");
			equipmentPartsService.addEquipmentParts(ep);
			 //---------------添加备件对应的适用设备信息---------------
	        String eIdsString=getRequest().getParameter("epApplicableequipment");
	        String eids[]=eIdsString.split(",");
	        EEPRelations []eepr=new EEPRelations[eids.length];
	        TdmEquipment equipment=new TdmEquipment();
	        EquipmentParts euqParts=new  EquipmentParts();
	        for(int i=0;i<eids.length;i++){
	        //	equipment=eepRelationsService.queryEqu(eids[i]);
	        	eepr[i]=new EEPRelations();
	        	Long idt=Long.parseLong(eids[i]);
	        	equipment.setId(idt);
	        	euqParts.setId(epid);
	        	eepr[i].setEquipmentParts(euqParts);
	        	eepr[i].setTdmEquipment(equipment);
	        	eepRelationsService.addEEPRelations(eepr[i]);
	        }
			out.print("{\"result\":\"success\"}");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			out.print("{\"result\":\"error\"}");
		}
	}
     
	//-----------------------------添加备件信息------------------------------------
	public void saveEquipmentParts()throws Exception{
		PrintWriter out = getResponse().getWriter();
		try{
			//生成备件id
			String id=equipmentPartsService.queryMaxEPNo();
			BigDecimal epid=new BigDecimal(Integer.parseInt(id)+1);
			String epId=Integer.parseInt(id)+1+"";
			EquipmentParts ep=new EquipmentParts();
		        ep.setId(epid);
		        ep.setEpStorehouse(getRequest().getParameter("epStorehouse"));
		        ep.setEpCode(getRequest().getParameter("epCode"));
		        ep.setEpName(getRequest().getParameter("epName"));
		        ep.setEpProperty(getRequest().getParameter("epProperty"));
		        ep.setEpLevel(getRequest().getParameter("epLevel"));
		        ep.setEpGuige(getRequest().getParameter("epGuige"));
		        ep.setEpBrand(getRequest().getParameter("epBrand"));
		        ep.setEpSupplier(getRequest().getParameter("epSupplier"));
		        ep.setEpMaxstock(new BigDecimal(Integer.parseInt(getRequest().getParameter("epMaxstock"))));
		        ep.setEpMinstock(new BigDecimal(Integer.parseInt(getRequest().getParameter("epMinstock"))));
		        ep.setEpActualstock(new BigDecimal(Integer.parseInt(getRequest().getParameter("epActualstock"))));
		        ep.setEpMeasurementunit(getRequest().getParameter("epMeasurementunit"));
		        ep.setEpApplicableequipment(getRequest().getParameter("epApplicableequipment"));
		        ep.setEpApplicableequipmentid(getRequest().getParameter("epApplicableequipmentid"));
		        ep.setEpStoragelocation(getRequest().getParameter("epStoragelocation"));
		        ep.setEpStockstate(getRequest().getParameter("epStockstate"));
		        ep.setEpRemark(getRequest().getParameter("epRemark"));
		        ep.setEpAverageprice(getRequest().getParameter("epInstoreprice"));
		        ep.setEpCycle(getRequest().getParameter("epIncycle"));
		        ep.setEpIsky("0");
		        equipmentPartsService.addEquipmentParts(ep);
		      //---------------添加备件对应的适用设备信息---------------
		        String eIdsString=getRequest().getParameter("epApplicableequipment");
		        String eids[]=eIdsString.split(",");
		        EEPRelations []eepr=new EEPRelations[eids.length];
		        TdmEquipment equipment=new TdmEquipment();
		        EquipmentParts euqParts=new  EquipmentParts();
		        for(int i=0;i<eids.length;i++){
		        //	equipment=eepRelationsService.queryEqu(eids[i]);
		        	eepr[i]=new EEPRelations();
		        	Long idt=Long.parseLong(eids[i]);
		        	equipment.setId(idt);
		        	euqParts.setId(epid);
		        	eepr[i].setEquipmentParts(euqParts);
		        	eepr[i].setTdmEquipment(equipment);
		        	eepRelationsService.addEEPRelations(eepr[i]);
		        }
		        
		        out.print("{\"result\":\"success\"}");
			    out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
				 out.print("{\"result\":\"error\"}");
			}
	}
	//------------------------------台账导入-----------------------------
	public void importExcelData()throws IOException{
		PrintWriter out=getResponse().getWriter();
		int num=0;
		int rownum=0;
		String msg="";
		int chongfuNum=0;  //检测是否存在重复数据
		try{
			//实例化一个工作簿对象
		  Workbook workBook=Workbook.getWorkbook(filePath);
		  //获取该工作表中的第一个工作表
		  Sheet sheet=workBook.getSheet(0);
		  //获取该工作表的行数，以供下面循环使用
		  int rowSize=sheet.getRows();
		  if(rowSize<2){
				out.print("{\"result\":\"error\"}");
				out.flush();
				out.close();
		  }
		  for (int i = 0; i < rowSize; i++) {
			  String a= sheet.getCell(0,i).getContents().trim();
			  String b= sheet.getCell(1,i).getContents().trim();
			  String c= sheet.getCell(2,i).getContents().trim();
			  String d= sheet.getCell(3,i).getContents().trim();
			  String e= sheet.getCell(4,i).getContents().trim();
			  String f= sheet.getCell(5,i).getContents().trim();
			  String g= sheet.getCell(6,i).getContents().trim();
			  String h= sheet.getCell(7,i).getContents().trim();
			  String ii= sheet.getCell(8,i).getContents().trim();
			  String j= sheet.getCell(9,i).getContents().trim();
			  String k= sheet.getCell(10,i).getContents().trim();
			  String l= sheet.getCell(11,i).getContents().trim();
			  String m= sheet.getCell(12,i).getContents().trim();
			  String n= sheet.getCell(13,i).getContents().trim();
			  String o= sheet.getCell(14,i).getContents().trim();
			  String p= sheet.getCell(15,i).getContents().trim();
			  String q= sheet.getCell(16,i).getContents().trim();
			  if((k!=null&&!k.equals(""))||(g!=null&&!g.equals(""))||(h!=null&&!h.equals(""))||(ii!=null&&!ii.equals(""))||(j!=null&&!j.equals(""))||(l!=null&&!l.equals(""))||(m!=null&&!m.equals(""))||(n!=null&&!n.equals(""))||(o!=null&&!o.equals(""))||(p!=null&&!p.equals(""))||(q!=null&&!q.equals(""))||(a!=null&&!a.equals(""))||(b!=null&&!b.equals(""))||(c!=null&&!c.equals(""))||(d!=null&&!d.equals(""))||(e!=null&&!e.equals(""))||(f!=null&&!f.equals(""))){
				  rownum++;
			  }
		 }
		  System.out.println("rownum:"+rownum);
		  List<EquipmentParts> eParts =new ArrayList<EquipmentParts>();
		//  List<String> wenTiHangShuList=new ArrayList<String>();
		  for(int i=1;i<rownum;i++)
		  {
			  String epStorehouse= sheet.getCell(0,i).getContents().trim();
			  String epCode= sheet.getCell(1,i).getContents().trim();
			  String epName= sheet.getCell(2,i).getContents().trim();
			  String epProperty= sheet.getCell(3,i).getContents().trim();
			  String epLevel= sheet.getCell(4,i).getContents().trim();
			  String epGuige= sheet.getCell(5,i).getContents().trim();
			  String epBrand= sheet.getCell(6,i).getContents().trim();
			  String epSupplier= sheet.getCell(7,i).getContents().trim();
			  String epAverageprice= sheet.getCell(8,i).getContents().trim();
			  String epCycle= sheet.getCell(9,i).getContents().trim();
			  String epMaxstock= sheet.getCell(10,i).getContents().trim();
			  String epMinstock= sheet.getCell(11,i).getContents().trim();
			  String epActualstock= sheet.getCell(12,i).getContents().trim();
			  String epStockstate= sheet.getCell(13,i).getContents().trim();
			  String epMeasurementunit= sheet.getCell(14,i).getContents().trim();
			  String epStoragelocation= sheet.getCell(15,i).getContents().trim();
			  String epRemark= sheet.getCell(16,i).getContents().trim();
               //去除所有空格的方法str.replace(" ", "")，去除开头和结尾空格的方法str.trim().
			  EquipmentParts ep1=new EquipmentParts();
			  if(epStorehouse==null||epStorehouse.equals("")||epName==null||epName.equals("")||epCode==null||epCode.equals("")){
				  out.print("{\"result\":\"success\",\"msg\":\"msgKong\",\"dangqianhangshu\":\""+i+"\"}");
				  break;
			  }
			  if(epStorehouse!=null&&isExistEPStorehouse(epStorehouse)!=null){ //查询当前仓库名称是否存在
				  ep1.setEpStorehouse(isExistEPStorehouse(epStorehouse));
			  }
			  else{
				  out.print("{\"result\":\"success\",\"msg\":\"msgErrorDep\",\"dangqianhangshu\":\""+i+"\"}");
				  break;	  
			  }
			  if(null!=epName && !"".equals(epName)&&null!=epCode && !"".equals(epCode)){
                  if(!isExistEP(epCode)){
                	  ep1.setEpCode(epCode);
    				  ep1.setEpName(epName);  
                  }
                  else{
                	  out.print("{\"result\":\"success\",\"msg\":\"msgErrorCF\",\"dangqianhangshu\":\""+i+"\"}");
    				  break;
                  }
				}
			  if(epSupplier!=null){
				if(isExistGYS(epSupplier)!=null){
				  ep1.setEpSupplier(isExistGYS(epSupplier));
				  }
				else{
					out.print("{\"result\":\"success\",\"msg\":\"msgErrorSup\",\"dangqianhangshu\":\""+i+"\"}");
				    break;
				}
			  }
			  else{
				  ep1.setEpSupplier(null);
			  }
				ep1.setEpProperty(epProperty);
				ep1.setEpLevel(epLevel);
				ep1.setEpGuige(epGuige);
				ep1.setEpBrand(epBrand);
				ep1.setEpAverageprice(epAverageprice);
				ep1.setEpCycle(epCycle);
				ep1.setEpMaxstock(new BigDecimal(epMaxstock));
				ep1.setEpMinstock(new BigDecimal(epMinstock));
				ep1.setEpActualstock(new BigDecimal(epActualstock));
				ep1.setEpStockstate(epStockstate);
				ep1.setEpMeasurementunit(epMeasurementunit);
				ep1.setEpStoragelocation(epStoragelocation);
				ep1.setEpRemark(epRemark);
				ep1.setEpIsky("0");
				ep1.setEpApplicableequipment("");
				if(!isExistEP(epCode)){
					String id=equipmentPartsService.queryMaxEPNo();
					BigDecimal epid=new BigDecimal(Integer.parseInt(id)+i);
					ep1.setId(epid);
					eParts.add(ep1);
				}	  
		  }
		  if(eParts.size()==rownum-1){
			  for(int j=0;j<eParts.size();j++){
				  equipmentPartsService.addEquipmentParts(eParts.get(j));
			  }
			  addMessage("导入成功！");
			  out.print("{\"result\":\"success\",\"msg\":\"msg\",\"dangqianhangshu\":\"dangqianhangshu\"}");
		  }
		  out.flush();
		  out.close();
		}catch(Exception ex){
			ex.printStackTrace();
			out.print("{\"result\":\"error\"}");
			out.flush();
			out.close();
		}
		
	}
	//-----------------------------修改备件信息------------------------------------
    public void updateEquipmentParts()throws Exception{
    		PrintWriter out = getResponse().getWriter();
    		try{
    			//获得备件id
    			String epId=this.getRequest().getParameter("id");
    			String rIds=eepRelationsService.queryRIdsByEP(epId);
    			String rId[]=rIds.split(",");
    			EEPRelations []rel=new EEPRelations[rId.length];
    			if(rIds!=null&&(!rIds.equals(""))){
	        	for(int j=0;j<rId.length;j++){
	        		rel[j]=eepRelationsService.queryRById(rId[j]);
	        	}
    			}
    			BigDecimal epid=new BigDecimal(epId);
    			EquipmentParts ep=equipmentPartsService.queryEPYuanListById(epId);
    			String equids=ep.getEpApplicableequipment();
    		        ep.setId(epid);
    		        ep.setEpStorehouse(getRequest().getParameter("epStorehouse"));
    		        ep.setEpCode(getRequest().getParameter("epCode"));
    		        ep.setEpName(getRequest().getParameter("epName"));
    		        ep.setEpProperty(getRequest().getParameter("epProperty"));
    		        ep.setEpLevel(getRequest().getParameter("epLevel"));
    		        ep.setEpGuige(getRequest().getParameter("epGuige"));
    		        ep.setEpBrand(getRequest().getParameter("epBrand"));
    		        ep.setEpSupplier(getRequest().getParameter("epSupplier"));
    		        ep.setEpMaxstock(new BigDecimal(Integer.parseInt(getRequest().getParameter("epMaxstock"))));
    		        ep.setEpMinstock(new BigDecimal(Integer.parseInt(getRequest().getParameter("epMinstock"))));
    		      //  ep.setEpActualstock(new BigDecimal(Integer.parseInt(getRequest().getParameter("epActualstock"))));
    		        ep.setEpMeasurementunit(getRequest().getParameter("epMeasurementunit"));
    		        ep.setEpApplicableequipment(getRequest().getParameter("epApplicableequipment"));
    		      //  ep.setEpApplicableequipmentid(getRequest().getParameter("epApplicableequipmentid"));
    		        ep.setEpStoragelocation(getRequest().getParameter("epStoragelocation"));
    		        ep.setEpStockstate(getRequest().getParameter("epStockstate"));
    		        ep.setEpRemark(getRequest().getParameter("epRemark"));
    		        ep.setEpAverageprice(getRequest().getParameter("epAverageprice"));
    		        ep.setEpCycle(getRequest().getParameter("epCycle"));
    		        ep.setEpIsky("0");
    		        ep.setEpRemark(getRequest().getParameter("epRemark"));
    		        equipmentPartsService.updateEquipmentParts(ep);
    		      //---------------添加备件对应的适用设备信息---------------
    		        String eIdsString=getRequest().getParameter("epApplicableequipment");
    		        if(equids!=null&&!equids.equals(eIdsString)){ 
    		        	if(rIds!=null&&(!rIds.equals(""))){
    		        	for(int m=0;m<rId.length;m++){
    		        		eepRelationsService.deleteEEPRelations(rel[m]);
    		        	}
    		        	}
    		        	String eids[]=eIdsString.split(",");
        		        EEPRelations []eepr=new EEPRelations[eids.length];
        		        TdmEquipment equipment=new TdmEquipment();
        		        EquipmentParts euqParts=new  EquipmentParts();
        		        for(int i=0;i<eids.length;i++){
        		        //	equipment=eepRelationsService.queryEqu(eids[i]);
        		        	eepr[i]=new EEPRelations();
        		        	Long idt=Long.parseLong(eids[i]);
        		        	equipment.setId(idt);
        		        	euqParts.setId(epid);
        		        	eepr[i].setEquipmentParts(euqParts);
        		        	eepr[i].setTdmEquipment(equipment);
        		        	eepRelationsService.addEEPRelations(eepr[i]);
        		        }
    		        }  		       		        
    		        out.print("{\"result\":\"success\"}");
    			    out.flush();
    				out.close();
    			} catch (Exception e) {
    				e.printStackTrace();
    				 out.print("{\"result\":\"error\"}");
    			}
	}

	
	/**
	 * 查询表单关系表中备件的信息----国伟添加的
	 * 
	 * 
	 */
	public void queryEquRelationByID() {
		try {
			String ids = StringUtil.encodingUrl(getRequest()
					.getParameter("ids")); // 国伟添加的根据IDS查询
			Map<String, String> filterMap = getPagerMap();
			if (null != ids && !"".equals(ids)) {
				ids = StringUtil.encodingUrl(ids);
				filterMap.put("ids", ids);// 国伟添加的IDS
			}
			PageResult result = equipmentPartsService
					.queryEquRelationByID(filterMap);
			String[] viewArray = { "id", "epCode", "epName", "epGuige",
					"epAverageprice", "epoutNum" };
			String str = getColumnJson(result, viewArray);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("application/XML,charset=GBK");
			response.setHeader("Charset", "GBK");
			response.setCharacterEncoding("GBK");
			response.setContentType("text/xml");
			PrintWriter out = getResponse().getWriter();
			out.print(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//查询当前仓库名称是否存在
	public String isExistEPStorehouse(String epStorehouseName){
		String sqlname = " select ORG_ID from sys_organization where org_name="+"'"+epStorehouseName+"'";
		List querylist = equipmentPartsService.queryDataBySql(sqlname);
		if(querylist.size()>0&&querylist!=null){
			return querylist.get(0).toString();
		}
		return null;
	}
	//查询当前供应商名称是否存在
	public String isExistGYS(String supplierName){
		String sqlname = "  select id from gwm_gongyingshang where GONGYINGSHANGNAME="+"'"+supplierName+"'";
		List querylist = equipmentPartsService.queryDataBySql(sqlname);
		if(querylist.size()>0&&querylist!=null){
			return querylist.get(0).toString();
		}
		return null;
	}
	//检测是否当前备件代码是否已存在
	public boolean isExistEP(String EPCode){
		String sqlname = " select * FROM tdm_equipment_parts where ep_code="+"'"+EPCode+"'";
		List querylist = equipmentPartsService.queryDataBySql(sqlname);
		if(querylist.size()>0&&querylist!=null){
			return true;
		}
		return false;
	}
	
}
